package org.buptsse.thread;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.message.BasicNameValuePair;
import org.buptsse.entity.MessageDetail;
import org.buptsse.utils.APPConstant;
import org.buptsse.utils.Base64Helper;
import org.buptsse.utils.ConnectionChecker;
import org.buptsse.utils.HttpHelper;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;

public class UpdateUserPhotoThread extends Thread{

	private Context context;
	private Handler handler;
	private String username,password;
	private Bitmap bitmap;
	
	public UpdateUserPhotoThread(Context context,Handler handler, String username,
								String password,Bitmap bitmap)
	{
		this.context=context;
		this.handler=handler;
		this.username=username;
		this.password=password;
		this.bitmap=bitmap;
	}
	
	public void run()
	{
		if(ConnectionChecker.CheckConnection(context, handler)==false)
		{
			return;
		}
		ArrayList<NameValuePair> param=new ArrayList<NameValuePair>();
		param.add(new BasicNameValuePair("name", username));
		param.add(new BasicNameValuePair("password", password));
		//System.out.println("username:"+username);
		//System.out.println("password:"+password);
		ByteArrayOutputStream os=new ByteArrayOutputStream();
		bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
		byte[] data=os.toByteArray();
		String pic_data=Base64Helper.encode(data, 0, data.length);
		param.add(new BasicNameValuePair("photo", pic_data));
		try {
			String result=HttpHelper.sendPost(APPConstant.uploadPhotoUrl, param);
			//System.out.println("result is:"+result);
			if(result.contains("success"))
			{
				//成功
				Message message= handler.obtainMessage(APPConstant.UploadPhotoFinish);
				handler.sendMessage(message);
				return;
			}else {
				//失败
				Message message=handler.obtainMessage(APPConstant.UploadPhotoError);
				handler.sendMessage(message);
				return;
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
